package cn.tedu.zhyl.iot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import cn.tedu.zhyl.base.exception.ServiceException;
import cn.tedu.zhyl.base.properties.IotProperties;
import cn.tedu.zhyl.iot.mapper.DeviceMapper;
import cn.tedu.zhyl.iot.pojo.dto.DeviceDto;
import cn.tedu.zhyl.iot.pojo.entity.Device;
import cn.tedu.zhyl.iot.service.IotService;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class IotServiceImpl implements IotService {
    @Autowired
    private Client client;
    @Autowired
    private IotProperties iotProperties;
    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public String getProductList(Integer page, Integer limit) {
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setIotInstanceId(iotProperties.getIotInstanceId());
        queryProductListRequest.setCurrentPage(page);
        queryProductListRequest.setPageSize(limit);
        try {
            QueryProductListResponse response = client.queryProductList(queryProductListRequest);
            return JSONUtil.toJsonStr(response.getBody().getData());
        } catch (Exception e) {
            throw new ServiceException(400, "阿里云获取设备异常！");
        }
    }

    @Override
    public void register(DeviceDto dto) throws Exception {
        RegisterDeviceRequest registerDeviceRequest = dto.getRegisterDeviceRequest();
        registerDeviceRequest.setDeviceName(dto.getDeviceName());
        registerDeviceRequest.setNickname(dto.nickname);
        registerDeviceRequest.setProductKey(dto.getProductKey());
        registerDeviceRequest.setIotInstanceId(iotProperties.getIotInstanceId());
        RegisterDeviceResponse registerDeviceResponse = client.registerDevice(registerDeviceRequest);
        if (Boolean.TRUE.equals(registerDeviceResponse.getBody().getSuccess())) {
            // 保存位置
            RegisterDeviceResponseBody.RegisterDeviceResponseBodyData iotData = registerDeviceResponse.getBody().getData();
            Device device = BeanUtil.toBean(dto, Device.class);
            device.setDeviceId(iotData.getIotId());
            device.setProductId(registerDeviceRequest.getProductKey());
            device.setNoteName(iotData.getNickname());

            QueryProductRequest queryProductRequest = new QueryProductRequest();
            queryProductRequest.setIotInstanceId(iotProperties.getIotInstanceId());
            queryProductRequest.setProductKey(registerDeviceRequest.getProductKey());
            QueryProductResponse queryProductResponse = client.queryProduct(queryProductRequest);
            device.setProductName(queryProductResponse.getBody().getData().getProductName());
            if (device.getLocationType().equals(0)) {
                device.setLocationType(-1);
            }
            try {
                deviceMapper.insert(device);
            } catch (Exception e) {
                DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
                deleteDeviceRequest.setIotInstanceId(iotProperties.getIotInstanceId());
                deleteDeviceRequest.setDeviceName(device.getDeviceName());
                deleteDeviceRequest.setIotId(device.getDeviceId());
                deleteDeviceRequest.setProductKey(device.getProductId());
                client.deleteDevice(deleteDeviceRequest);
                throw new ServiceException(400, "该老人/位置已绑定该产品，请重新选择");
            }
            return;
        }
        throw new ServiceException(400, registerDeviceResponse.getBody().getErrorMessage());
    }

    @Override
    public List<Device> getDeviceList(String productId) {
        QueryDeviceRequest queryDeviceRequest = new QueryDeviceRequest();
        queryDeviceRequest.setIotInstanceId(iotProperties.getIotInstanceId());
        queryDeviceRequest.setProductKey(productId);
        try {
            QueryDeviceResponse queryDeviceResponse = client.queryDevice(queryDeviceRequest);
            if (Boolean.TRUE.equals(queryDeviceResponse.getBody().getSuccess())) {
                QueryDeviceResponseBody.QueryDeviceResponseBodyData data = queryDeviceResponse.getBody().getData();
                if (data == null) {
                    return null;
                }
                List<QueryDeviceResponseBody.QueryDeviceResponseBodyDataDeviceInfo> deviceInfo = data.getDeviceInfo();
                List<String> deviceNames = deviceInfo.stream().map(item -> item.getDeviceName()).collect(Collectors.toList());
                QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
                deviceQueryWrapper.in("device_name", deviceNames);
                deviceQueryWrapper.eq("product_id", productId);
                log.debug("根据阿里云的设备id，数据库查询,{}", deviceNames);
                List<Device> deviceList = deviceMapper.selectList(deviceQueryWrapper);
                return deviceList;
            } else {
                throw new ServiceException(400, queryDeviceResponse.getBody().getErrorMessage());
            }
        } catch (Exception e) {
            throw new ServiceException(400, "该产品不存在");
        }

    }

    @Override
    public void delDevice(String pk, String deviceName) throws Exception {
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setProductKey(pk);
        deleteDeviceRequest.setIotInstanceId(iotProperties.getIotInstanceId());
        deleteDeviceRequest.setDeviceName(deviceName);
        DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
        if (Boolean.TRUE.equals(deleteDeviceResponse.getBody().getSuccess())) {
            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
            deviceQueryWrapper.eq("product_id", pk);
            deviceQueryWrapper.eq("device_nam", deviceName);
            deviceMapper.delete(deviceQueryWrapper);
        } else {
            throw new ServiceException(400, deleteDeviceResponse.getBody().getErrorMessage());
        }


    }

    @Override
    public Device getDeviceDetail(String productId, String deviceName) throws Exception {
        QueryDeviceDetailRequest queryDeviceDetailRequest = new QueryDeviceDetailRequest();
        queryDeviceDetailRequest.setDeviceName(deviceName);
        queryDeviceDetailRequest.setProductKey(productId);
        queryDeviceDetailRequest.setIotInstanceId(iotProperties.getIotInstanceId());
        QueryDeviceDetailResponse queryDeviceDetailResponse = client.queryDeviceDetail(queryDeviceDetailRequest);
        if(Boolean.TRUE.equals(queryDeviceDetailResponse.getBody().getSuccess())){
            QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData deviceIotInfo = queryDeviceDetailResponse.getBody().getData();
            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
            deviceQueryWrapper.eq("product_id",productId);
            deviceQueryWrapper.eq("device_name",deviceName);
            Device device = deviceMapper.selectOne(deviceQueryWrapper);
            return device;
        }else {
            throw new ServiceException(400,queryDeviceDetailResponse.getBody().getErrorMessage());
        }
    }

    @Override
    public String getDeviceStatus(String productId, String deviceName) throws Exception {
        GetDeviceStatusRequest getDeviceStatusRequest = new GetDeviceStatusRequest();
        getDeviceStatusRequest.setIotInstanceId(iotProperties.getIotInstanceId());
        getDeviceStatusRequest.setProductKey(productId);
        getDeviceStatusRequest.setDeviceName(deviceName);
        GetDeviceStatusResponse deviceStatus = client.getDeviceStatus(getDeviceStatusRequest);
       if (Boolean.TRUE.equals(deviceStatus.getBody().getSuccess())){
           String status = deviceStatus.getBody().getData().getStatus();
           return status;
       }
       throw new ServiceException(400,deviceStatus.getBody().getErrorMessage());
    }

    @Override
    public String getThingModelData(String productId, String deviceName) throws Exception {
        QueryThingModelPublishedRequest queryThingModelRequest = new QueryThingModelPublishedRequest();
        queryThingModelRequest.setIotInstanceId(iotProperties.getIotInstanceId());
        queryThingModelRequest.setProductKey(productId);
        QueryThingModelPublishedResponse queryThingModelPublishedResponse = client.queryThingModelPublished(queryThingModelRequest);
        if(Boolean.TRUE.equals(queryThingModelPublishedResponse.getBody().getSuccess())){
            return queryThingModelPublishedResponse.getBody().getData().getThingModelJson();
        }
        return "";
    }
}
